const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');
const moment = require('moment');
moment.locale('zh-cn');
const Schema = mongoose.Schema;

const UserSchema = new Schema({
  email: {
      type: String,
      required: [true, '邮箱必须填写。'],
      unique: true,
      validate: {
          validator: function (v) {
              return /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(v);
          },
          message: '邮箱格式不正确。'
      }
  },
  username: {
      type: String,
      required: [true, '用户名必须填写。'],
      minlength: 2,
      maxlength: 45,
      unique: true,
      validate: {
          validator: async function (v) {
              const user = await mongoose.models.User.findOne({ username: v });
              return!user;
          },
          message: '用户名已经存在。'
      }
  },
  createdAt: {
      type: Date,
      get: function () {
          return moment(this.createdAt).format("YYYY-MM-DD HH:mm:ss");
      }
  },
  updatedAt: {
      type: Date,
      default: Date.now,
      get: function () {
          return moment(this._doc.updatedAt).format("YYYY-MM-DD HH:mm:ss");
      }
  },
  password: {
      type: String,
      required: [true, '密码必须填写。'],
  },
  avatar: String,
  nickname: {
      type: String,
      required: [true, '昵称必须填写。'],
      minlength: 2,
      maxlength: 45
  },
  sex: {
      type: Number,
      required: [true, '性别必须填写。'],
      enum: [0, 1, 2],
      validate: {
          validator: function (v) {
              return [0, 1, 2].includes(v);
          },
          message: '性别的值必须是，男性：0 女性：1 未选择：2。'
      }
  },
  company: String,
  introduce: String,
  role: {
      type: Number,
      required: [true, '用户组必须选择。'],
      enum: [0, 50, 100],
      validate: {
          validator: function (v) {
              return [0, 50, 100].includes(v);
          },
          message: '用户组的值必须是，普通用户：0 管理员：100。'
      }
  },
  likeBooks: [{ type: Schema.Types.ObjectId, ref: 'Book' }],
}, {
  timestamps: true
});

UserSchema.pre('save', function (next) {
    const password = this.password;
    // 检查是否为空
    if (!password) {
        return next(new Error('密码必须填写。'));
    }
    // 检查长度
    if (password.length < 6 || password.length > 45) {
        return next(new Error('密码长度必须是6 ~ 45之间。'));
    }
    // 对密码进行哈希处理
    this.password = bcrypt.hashSync(password, 10);
    next();
});



const User = mongoose.model('User', UserSchema);
module.exports = User;
